package com.zzptc.myapp1130bookreader;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zzptc.myapp1130bookreader.Bean.Book;
import com.zzptc.myapp1130bookreader.Bean.User;

import org.litepal.LitePal;

public class LoginActivity extends AppCompatActivity {
    private EditText usdedit,psdedit;
    private Button loginbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getUser();
        initView();
        setListener();
        getBook();
    }

    private void getBook() {
        new Book(0,"虐杀原形之雷欧","张三",R.drawable.nsyx).save();
        new Book(0,"生化危机之二仙桥","李四",R.drawable.shweiji).save();
        new Book(0,"艾达.王新闻","王五",R.drawable.aidawang).save();
        new Book(0,"艾达王之喊麦","王五",R.drawable.wangaida).save();
        new Book(0,"求生之路之赶集","赵六",R.drawable.qiushengzhilu).save();
    }

    private void getUser() {
        new User(0,"张三","123").save();
        new User(0,"李四","456").save();
        new User(0,"王五","789").save();
        new User(0,"赵六","68910").save();

    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usdedit.getText().toString().trim();
                String psd=psdedit.getText().toString().trim();
                User u=confirmUser(usn,psd);
                if (u==null){
                    //登录失败 有这个人？！
                }else {
                    Intent it=new Intent(LoginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("userid",u.getId());
                    editor.putString("username",u.getUsername());
                    editor.apply();
                    startActivity(it);
                }

            }
        });

    }

    private User confirmUser(String usn, String psd) {
        for (User u: LitePal.findAll(User.class)){
            if (u.getUsername().equals(usn)&&u.getPassword().equals(psd)){
                return u;
            }
        }


        return null;
    }

    private void initView() {
        usdedit=findViewById(R.id.usdedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);


    }
}
